<template>
  <div class="common-list-container__v2">
    <!--s 头部搜索栏 -->
    <div ref="tableHeaderContainer" class="common-list-header__v2">
      <div class="input-with-append-search flex-x mar-r-24">
        <el-input class="search-input" :placeholder="$t('servicePrice.list.placeholder1')" v-model="searchParams.keyword" v-trim:blur>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
          <el-button type="primary" slot="append" @click="handleSearch" native-type="submit" v-track="$track.formatParams('KEYWORD_SEARCH')">{{$t('common.base.search')}}</el-button>
        </el-input>
        <el-button type="plain-third" class="ml_12" @click="resetParams" v-track="$track.formatParams('RESET_SEARCH')">{{$t('common.base.reset')}}</el-button>
      </div>
      <span class="advanced-search-btn pointer" @click.self="panelSearchAdvancedToggle">
        <i class="iconfont icon-filter" @click.self="panelSearchAdvancedToggle"></i>
        {{$t('common.base.advancedSearch')}}
      </span>
    </div>
    <!--e 头部搜索栏 -->
    <!--s 内容 -->
    <div class="common-list-view__v2 mt_12">
      <div ref="tableDoContainer" class="common-list-view-header__v2">
        <div  class="operate-box__left flex-x jus-bet">
          <!-- 新建 -->
          <!-- TODO SERVICE_CREATE 权限 -->
          <el-button v-if="allowCreate" type="primary" icon="el-icon-plus" @click="handleAdd" v-track="$track.formatParams('TO_CREATE')">{{$t('common.base.create')}}</el-button>
          <!-- TODO SERVICE_EDIT 权限 -->
          <!-- 批量编辑 -->
          <el-button
            v-if="allowEdit"
            type="plain-third"
            @click="Alledit"
            v-track="$track.formatParams('BATCH_EDIT')"
          >
            <i class="iconfont icon-edit-square"></i>{{$t('common.base.bulkEdit')}}
          </el-button>

          <el-button v-if="allowDelete" type="plain-third" class="cur-point ml_12" @click="handleDelete" v-track="$track.formatParams('DELETE')">
            <i class="iconfont icon-delete task-font14"></i>
            {{$t('common.base.delete')}}
          </el-button>
        </div>
        
        <div  class="operate-box__right action-button-group" v-if="allowExportIN">
          <!-- 更多操作 -->
          <el-dropdown>
            <div class="cur-point" v-if="isButtonDisplayed">
              <span>{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu class="service-price-dropdown" slot="dropdown">
              <el-dropdown-item v-if="isButtonDisplayed && !isExperienceEdition && allowImport">
                <div @click="handleImport" v-track="$track.formatParams('IMPORT_SERVICE_PRICE', null, 'MORE_ACTIONS')">{{$t('servicePrice.list.import')}}</div>
              </el-dropdown-item>
              
              <el-dropdown-item v-if="isButtonDisplayed && allowExport">
                <div @click="handleExport(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              
              <el-dropdown-item v-if="isButtonDisplayed && allowExport">
                <div @click="handleExport(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
              <!-- 导入导出区域定价 -->
              <template v-if="isAreaPrice">
                <el-dropdown-item>
                  <div @click="handleImportAreaPrice">{{$t('common.base.importAreaPrice')}}</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="handleExportAreaPrice">{{$t('common.base.exportAreaPrice')}}</div>
                </el-dropdown-item>
              </template>
              <el-dropdown-item v-if="!isExperienceEdition && allowImport">
                <span class="dropdown-item" @click="importEditPart" v-track="$track.formatParams('BATCH_UPDATE', null, 'MORE_ACTIONS')">{{$t('common.base.batchUpdate')}}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <!-- <div
        ref="BaseSelectionBarComponent"
        v-show="multipleSelection.length"
        class="common-list-selection__v2 mt_8"
      >
        已选择
        <span>
          {{ multipleSelection.length }}
        </span>
        条
        <span class="pointer" @click="toggleSelection">清空</span>
      </div> -->
      <!--s 表格 -->
      <el-table
        ref="table"
        class="common-list-table__v2 mt_8 bbx-normal-list-box"
        stripe
        v-loading="loading"
        :data="tableData"
        :highlight-current-row="false"
        :border="true"
        :height="tableContainerHeight"
        row-key="id"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        @header-dragend="headerDragend"
        header-row-class-name="common-list-table-header__v2"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!loading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
        </template>
        <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
          :reserve-selection="true"
        ></el-table-column>
        <template v-for="column in columns">
          <el-table-column
            v-if="column && column.show"
            show-overflow-tooltip
            :align="column.align"
            :key="column.field"
            :label="column.displayName"
            :min-width="column.minWidth"
            :prop="column.field"
            :sortable="column.sortable"
            :width="column.width"
            :resizable="true"
            :fixed="column.fixed"
          >
            <template slot-scope="scope">
              <!-- 处理示例数据 -->
              <template v-if="column.field === 'name'">
                <sample-tooltip :row="scope.row">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <el-tooltip
                      :content="scope.row[column.field]"
                      placement="top"
                      :disabled="!isContentTooltip"
                    >
                      <div class="customer-name-block">
                        <div class="view-detail-btn"
                          @click.stop.prevent="handleOpenDetailView(scope.row)">
                          <pre class="pre-text">{{ scope.row[column.field] }}</pre>
                        </div>
                      </div>
                    </el-tooltip>
                  </template>
                </sample-tooltip>
              </template>
              <template v-else-if="column.renderCell">
                <template v-if="column.field === 'salePrice' ">
                  {{ scope.row | fmt_salePrice_currency}}
                </template>
                <template v-else-if="column.field === 'costPrice' ">
                  {{ scope.row[column.field] }} <span class="ml-3" v-if="internationalGray" >{{ scope.row.costPriceCurrency || 'CNY' }}</span>
                </template>
                <base-table-cell v-else :render-cell="column.renderCell" :column="column" :row="scope.row"></base-table-cell>
              </template>
              <template v-else>
                {{ $formatFormField(column, scope.row) }}
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <!--e 表格 -->
      <!--s 分页信息 -->
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-12 pad-b-16 bg-w pad-t-16">
        <div class="list-info" >
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ servicePricePage.total || 0 }}</span>
          </i18n>
          <template v-if="multipleSelection&&multipleSelection.length>0">
            <i18n path="common.base.table.selectedNth">
              <span place="count" class="color-primary pad-l-5 pad-r-5">{{ multipleSelection.length }}</span>
            </i18n>
            <span class="color-primary cur-point" @click="toggleSelection">{{$t('common.base.clear')}}</span>
          </template>
        </div>
        <el-pagination
          background
          hide-on-single-page
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="servicePricePage.total"
        >
        </el-pagination>
      </div>
      <!--e 分页信息 -->
    </div>
    <!--e 内容 -->
    
    <!-- 高级搜索框 -->
    <base-search-drawer
      :show.sync="visible"
      :storage-key="advancedColumnNumStorageKey"
      @reset="resetParams"
      @search="handleAdvancedSearch"
      @changeWidth="setAdvanceSearchColumn"
      @getColumnNum="setAdvanceSearchColumn"
    >
      <base-search-panel ref="searchPanel" :column-num="columnNum" :fields="advanceSearchColumn"/>
    </base-search-drawer>

    <!-- 导出 -->
    <base-export-group
      ref="exportPanel"
      :alert="exportAlert"
      :columns="exportColumnList"
      :build-params="buildExportParams"
      :group="true"
      :validate="checkExportCount"
      :emulateJSON="false"
      method="post"
      :action="servicePriceListExport"
    />
     <!-- S 批量编辑 -->

      <batch-editing-customer-dialog
        ref="batchEditingCustomerDialog"
        :config="config"
        :selected-ids="selectedIds"
        :select-list="multipleSelection"
        @update="updatEedit"
      ></batch-editing-customer-dialog>
      <!-- E 批量编辑 -->
    <!-- 导入 -->
    <base-import
      :title="$t('servicePrice.list.importTemplate')"
      ref="importModal"
      :action="servicePriceListImport"
      :template-url="servicePriceListImportTem"
    >
    </base-import>
    <!-- 导出区域定价 -->
    <base-export-group
      ref="exportAreaPricePanel"
      :alert="exportAlert"
      :columns="[]"
      :build-params="buildExportAreaPriceParams"
      :validate="checkExportAreaPriceCount"
      :needchoose-break="false"
      method="post"
      :action="areaPriceExport"
    />
    <!-- 导入区域定价 -->
    <base-import
      :title="$t('common.base.importAreaPriceTemplate')"
      ref="importAreaPriceModal"
      :action="servicePriceListImportAreaPrice"
      :template-url="servicePriceListImportAreaPriceTem"
    >
    </base-import>
    <part-import ref="importEditPart" 
                 v-if="allowEdit" :title="$t('common.form.type.serviceIterm')" :selected="multipleSelection" :total="servicePricePage.total"
                 :name="$t('servicePrice.list.bulkUpdate')"
                 :template-url="servicePriceListtemplate" 
                 :template-blank-url="servicePriceblankTemplate"
                 :template-params="editPartPostParam"
                 :action="servicePriceListImportUpdate" @success="importSucc">
      <el-popover slot="explain" trigger="hover">
        <ul class="title-explain">
          <li>{{$t('servicePrice.list.tip1')}}</li>
          <li>{{$t('servicePrice.list.tip2')}}</li>
        </ul>
      </el-popover>
    </part-import>

  </div>
</template>

<script>
// pageDes 服务管理-服务项目列表
import * as _ from 'lodash';
// api
import * as ServicePriceApi from '@src/api/ServicePriceApi';
// model
import Page from '@model/Page';
import {getColumnFields, getAdvancedFields} from './fields';
// components
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import BaseTableCell from 'packages/BaseTableCell';
import BatchEditingCustomerDialog from './components/BatchEditingCustomerDialog.vue';
import PartImport from '@src/modules/partV2/category/components/PartImport.vue';
/* util */
import { storageGet, storageSet } from "@src/util/storageV2";
import { checkButtonDisplayed, getRootWindow } from '@src/util/dom';
import { formatDate, useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts'
/* export & import */
import { servicePriceListExport, areaPriceExport } from '@src/api/Export';
import { servicePriceListImportTem, servicePriceListImport, servicePriceListImportAreaPrice, servicePriceListImportAreaPriceTem, servicePriceblankTemplate, servicePriceListtemplate, servicePriceListImportUpdate } from '@src/api/Import';
/* mixin */
import VersionMixin from '@src/mixins/versionMixin/index.ts'

import AuthUtil from '@src/util/auth';
import { safeNewDate } from '@src/util/time';
import { openAccurateTab } from '@src/util/platform'
import { defaultTableData } from '@src/util/table'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

const SERVICE_PRICE_LIST_KEY = 'service_price_list';
const SERVICE_PRICE_PAGE_SIZE_KEY = 'service_price_page_size';
const MAXCHECK = 500;
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()

export default {
  name: 'service-price-list',
  mixins: [VersionMixin],
  inject: ['initData'],
  data() {
    return {
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      selectColumnState:'servicePriceList',
      multipleSelection: [],
      editPartPostParam:{},
      searchParams: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
        sortBy: {}
        // sorts: []
      },
      fullSearchParams: {},
      servicePricePage: new Page(),
      serviceItemsTypes: [],

      visible: false,
      columns: [],
      columnNum: 1,
      exportColumnList: [], // fieldInfos
      fieldInfos:[],
      loading: true,
      advancedColumnNumStorageKey: StorageKeyEnum.ServicePriceListAdvancedColumnNum,
      servicePriceListExport,
      servicePriceListImportTem,
      servicePriceListImport,
      areaPriceExport,
      servicePriceListImportAreaPrice,
      servicePriceListImportAreaPriceTem,
      servicePriceblankTemplate,
      servicePriceListtemplate,
      servicePriceListImportUpdate,
      auths: {},
      tableContainerHeight:'440px',
      internationalGray
    }
  },
  computed: {
    // 处理时间后的列表数据
    tableData(){
      return disposeFormListViewTime(this.servicePricePage.list, this.columns)
    },
    config(){
      return {
        fields:this.fieldInfos
      }
    },
    // 高级搜索字段
    advanceSearchColumn() {
      return [
        ...getAdvancedFields(this),
        // ...this.extraAdvanceFields
      ].filter(item => 
        item.isSearch && item.isSearch == 1
      );
    },
    /** 当前选中的ids */
    selectedIds() {
      return this.multipleSelection.map((p) => p.id);
    },
    /* 新建权限*/
    allowCreate() {
      return AuthUtil.hasAuth(this.auths, 'SERVICE_CREATE');
    },
    /* 编辑服务*/
    allowEdit() {
      return AuthUtil.hasAuth(this.auths, 'SERVICE_EDIT');
    },
    /* 导入导出 */
    allowExportIN() {
      return this.allowImport || this.allowExport || this.isAreaPrice
    },
    allowImport() {
      return AuthUtil.hasAuth(this.auths, 'SERVICE_IMPORT') && this.allowCreate
    },
    allowExport() {
      return AuthUtil.hasAuth(this.auths, 'SERVICE_EXPORT');
    },
    allowDelete() {
      return AuthUtil.hasAuth(this.auths, 'SERVICE_DELETE');
    },
    // 是否开启区域定价灰度
    isAreaPrice() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.areaPrice
    },
    // 是否开放服务商查看服务项目和物料的价格信息
    serviceProviderShowPrice() {
      try {
        const RootWindow = getRootWindow(window);
        const InitData = RootWindow._init ? JSON.parse(RootWindow._init) : {};
        return InitData.serviceProviderShowPrice ?? true;
      } catch (error) {
        return true;
      }
    }
  },
  methods: {
    importEditPart(){ 
      if(!this.allowEdit) return;    
      let param = {
        ids: ''
      };

      // if (!this.selected.length) {
      // return this.$platform.alert('您尚未选择数据，请选择数据后点击批量更新');
      // }

      if(this.multipleSelection.length > 0) param.ids = this.multipleSelection.map(item => item.id).join(',');
      let arr = [];
      this.editPartPostParam = param;
      for (let i in param) {
        arr.push(`${i }=${ param[i]}`);
      }
      this.editPartParam = arr.join('&');

      let instance = this.$refs.importEditPart;
      instance.open(param);
    },
    importSucc(){
      window.parent.showExportList();
      window.parent.exportPopoverToggle(true);
      // this.search();
    },
    /**
     * @description 批量编辑成功
     */
    updatEedit() {
      this.searchParams.pageSize = 10;
      this.searchParams.pageNum = 1;
      this.toggleSelection()
      this.search();
      // this.fetchServicePriceList(this.fullSearchParams);
    },
    /**
     * @description 批量编辑
     */
    Alledit() {
      const {
        selectedIds
      } = this;
      if (!selectedIds.length) {
        this.$platform.alert(this.$t('servicePrice.list.tip3'));
        return;
      }
      window.TDAPP.onEvent(this.$t('servicePrice.list.label1'));
      this.$refs.batchEditingCustomerDialog.open();
    },
    // 获取页面的初始化数据
    fetchInitData() {
      ServicePriceApi.servicePriceListInfo()
        .then(res => {
          if(res.status == 0) {
            this.fieldInfos = res.data.fieldInfos
            this.serviceItemsTypes = res.data.serviceItemsTypes

            // 是否隐藏销售单价和出库价
            if(!this.serviceProviderShowPrice) {
              this.fieldInfos = this.fieldInfos.filter(field => field.fieldName !== 'salePrice' && field.fieldName !== 'costPrice')
            }

            this.buildExportColunms();
          }
        })
    },

    /** 获取列表数据 */
    fetchServicePriceList(searchParams) {
      let params = {
        ...this.searchParams,
        ...searchParams
      }

      this.fullSearchParams = params

      // console.log('搜索参数: ', params);
      
      this.loading = true;
      ServicePriceApi.servicePriceList(params)
        .then(res => {
          if(res.status == 0) {
            this.loading = false;
            this.servicePricePage = res.data || [];
          }
        })
        .catch(err => {console.error(err)})
        .finally(err => {this.loading = false})
    },

    /** 搜索事件 */
    search (isAdvanced) {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      advancedSearchParams.isAdvanced = isAdvanced || 0

      this.fetchServicePriceList(advancedSearchParams);
      this.closeDrawer();
    },
    // 点击搜索按钮
    handleSearch() {
      this.initPage();
      this.search();
    },
    // 高级搜索 ——> 点击搜索按钮
    handleAdvancedSearch() {
      this.initPage();
      this.search(1);
    },

    // 新建
    handleAdd() {
      if(!this.allowCreate) return;
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: 'servicePriceCreateView',
      //   title: '新建服务项目',
      //   url: `/service/price/createView/0`,
      //   close: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServicePriceCreateView,
        fromId
      })
    },

    // 删除
    handleDelete() {
      const { selectedIds } = this;
      if (!selectedIds.length) {
        this.$platform.alert(this.$t('servicePrice.list.tip4'));
        return;
      }

      this.$confirm(this.$t('servicePrice.list.tip5'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(async () => {
          const params = {
            ids: selectedIds.join(',')
          }
          const { status } = await ServicePriceApi.servicePriceDelete(params);
          if (status == 0) {
            this.$platform.alert(this.$t('common.base.deleteSuccess'));
            this.toggleClearSelection()
            this.search()
          }
        })
        .catch(() => { });
    },

    // 清空选择框
    toggleClearSelection() {
      this.multipleSelection = [];
      this.$refs.table.clearSelection();
    },

    // 导入
    handleImport() {
      this.$refs.importModal.open();
    },
    // 导入区域定价
    handleImportAreaPrice() {
      this.$refs.importAreaPriceModal.open();
    },

    /**
     * @description: 导出（全部）
     * @param {Boolean} isExportAll 是否导出全部
     */
    async handleExport(isExportAll) {
      let ids = [];
      let fileName = this.$t('servicePrice.list.fileName', {data: formatDate(safeNewDate(), 'YYYY-MM-DD')});
      if (!isExportAll) {
        if (!this.multipleSelection.length) return this.$platform.alert(this.$t('common.base.tip.exportUnChooseTip'));
        ids = this.selectedIds;
      }

      const ExportPanelComponent = this.$refs.exportPanel
      if (!ExportPanelComponent) {
        return console.warn('Caused: $refs.exportPanel is Empty')
      }

      const LocalStorageData = await this.getLocalStorageData()
      let exportCheckedData = LocalStorageData.exportCheckedData

      if (!exportCheckedData) {
        exportCheckedData = {
          checkedGroup: [],
          checkedMap: {},
          isCheckedAll: false,
          tooltip: true
        }
      }

      ExportPanelComponent.open(ids, fileName, false, exportCheckedData)
    },
    // 导出区域定价
    handleExportAreaPrice() {
      let ids = this.selectedIds
      const ExportAreaPricePanelComponent = this.$refs.exportAreaPricePanel
      if (!ExportAreaPricePanelComponent) {
        return console.warn('Caused: $refs.exportAreaPricePanel is Empty')
      }
      // 导出区域定价直接调用导出方法，不需要显示导出选择列弹窗了
      let params = this.buildExportAreaPriceParams()
      
      return navigator.userAgent.indexOf('Trident') >= 0
        ? ExportAreaPricePanelComponent.formExport(params)
        : ExportAreaPricePanelComponent.ajaxExport(params)
    },

    // 表格打开详情
    handleOpenDetailView(item) {
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `servicePriceDetailView_${item.id}`,
      //   title: '服务项目详情',
      //   url: `/service/price/view/${item.id}`,
      //   close: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServicePriceDetailView,
        key: item.id,
        fromId
      })
    },

    // 表格按钮编辑
    handleOpenEditView(item) {
      if(!this.allowEdit) return;
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `servicePriceView_${item.id}`,
      //   title: '编辑服务项目',
      //   url: `/service/price/edit/${item.id}?noHistory=1`,
      //   close: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServicePriceView,
        key: item.id,
        params: 'from=list',
        fromId
      })
    },
    
    // 表格修改状态
    handleChangeStatus(row){
      let params = {
        id: row.id,
        state: Number(!row.state)
      }

      // row.disabled = true;
      ServicePriceApi.servicePriceChangeStatus(params)
        .then(result => {
          if(result.status == 0){
            row.state = result.data.state;
          } else {
            row.state = !row.state;
            this.$platform.alert(result.message);
          }
        })
        .catch(err => console.warn(err))
        .finally(() => {
          row.disabled = false;
        })
    },

    /** 打开高级搜索 */
    panelSearchAdvancedToggle() {
      this.visible = true;
    },

    /** 关闭高级搜索弹框 */
    closeDrawer(){
      this.visible = false;
    },

    resetParams () {
      const fromId = window.frameElement.getAttribute('id');
      this.$platform.refreshTab(fromId);
    },

    /** 设置高级搜索展示列数 */
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },

    /** 表格选择操作: zr_todo */
    handleSelection(selection) {
      let selected = [];

      selected = [
        ...this.multipleSelection,
        ...selection.filter(item => {
          return !this.multipleSelection.some(s => s.id === item.id);
        })
      ];

      if(selected.length > MAXCHECK) {
        return this.$platform.alert(this.$t('common.base.tip.selectAtMostTip', {max: MAXCHECK}));
      }
      
      this.multipleSelection = selection;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },

    /** 排序变化  */
    sortChange(option) {
      let {column, order, prop} = option;
      this.searchParams.sortBy = {};

      if(column !== null) {
        this.searchParams.sortBy[prop] = order === 'ascending' ? true : false;
      }
      
      this.search();
    },

    /** 清空选择框 */
    toggleSelection() {
      this.multipleSelection = [];
      this.$refs.table.clearSelection();
    },

    /** 页码跳转 */
    jump(pageNum) {
      this.searchParams.pageNum = pageNum;
      this.servicePricePage.list = [];
      this.search();
    },

    /** 页大小改变 */
    handleSizeChange(pageSize) {
      this.saveDataToStorage(SERVICE_PRICE_PAGE_SIZE_KEY, pageSize);
      this.initPage(1, pageSize);
      this.search();
    },
    /**
     * @description 初始化page
     */
    initPage(pageNum = 1, pageSize = this.searchParams.pageSize) {
      this.searchParams.pageNum = pageNum;
      this.searchParams.pageSize = pageSize;
    },
    
    // 构建导出参数
    buildExportParams(checkedMap, ids, exportOneRow) {
      const { systemChecked } = checkedMap
      
      let exportAll = !ids || !ids.length;

      const exportSearchModel = { 
        ...this.fullSearchParams,
        exportTotal: exportAll ? this.servicePricePage.total : this.selectedIds.length,
      }

      let params = {
        dataTotal: this.servicePricePage.total,
        servicePriceSearchModel: JSON.stringify(exportSearchModel)
      };

      // 系统信息
      let export_sys = this.exportData('systemChecked', systemChecked)

      // params['exportOneRow'] = exportOneRow
      params['data'] = exportAll ? '' : this.selectedIds.join(',')
      params['checked'] = export_sys
        .map((item) => {
          return item;
        })
        .join(',');
      return params;
    },
    // 构建导出区域定价参数
    buildExportAreaPriceParams() {
      const ids = this.selectedIds
      let exportAll = !ids || !ids.length
      const exportSearchModel = { 
        ...this.fullSearchParams,
        exportTotal: exportAll ? this.servicePricePage.total : ids.length,
      }
      let params = {
        ids,
        type: 'serviceItem',
        exportTotal: exportAll ? this.servicePricePage.total : ids.length,
        searchModel: JSON.stringify(exportSearchModel)
      }
      return params
    },

    /**
     * 导出数据
     */
    exportData(type, list = []) {
      const export_list = this.exportColumnList
      let xlistColumns = []
      export_list.forEach((xlist, i) => {
        if(xlist.value === type) xlistColumns = xlist.columns
      })

      return xlistColumns.map(v => {
        let bool = list.some(item => {
          if (v.exportAlias) {
            return v.exportAlias === item
          } 
          return v.fieldName === item
          
        })
        if (bool) {
          return v.exportAlias ? v.exportAlias : v.fieldName
        }
      }).filter(item => {
        return item
      })
    },

    buildExportColunms() {
      const systemInfo = {
        label: this.$t('common.form.fieldGroupName.system2'),
        value: 'systemChecked',
        columns: this.fieldInfos.map(item => {
            item.export = true
            item.field = item.fieldName
            item.label = item.displayName
            return item
          })
      }

      this.exportColumnList = [systemInfo] // TODO 字段要通过接口获取
    },

    // 导出提示
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },

     /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.servicePricePage.total > max
        ? this.$t('common.base.tip.exportMostTip')
        : null;
    },
    checkExportAreaPriceCount() {
      return null
    },

    // 获取本地localstorage
    getLocalStorageData() {
      const dataStr = storageGet(SERVICE_PRICE_LIST_KEY, '{}');
      return JSON.parse(dataStr);
    },

    // 保存数据到本地localstorage
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(SERVICE_PRICE_LIST_KEY, JSON.stringify(data));
    },

    /**
     * @des 表单拖拽钩子函数
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (
            item.fieldName === column.property
            || item.field === column.property
          ) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },

    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map((c) => ({
        field: c.field,
        show: c.show,
        width: c.width,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus[
          `${this.selectColumnState}`
        ] = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = {
          [`${this.selectColumnState}`]: columnsList,
        };
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    // 构建表格列
    buildTableColumn() {
      let baseColumns = getColumnFields(this);
      const localStorageData = this.getLocalStorageData();
      let columnStatus = (localStorageData.columnStatus && localStorageData.columnStatus[this.selectColumnState]) || [];
      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col) => (acc[col.field] = col) && acc, {});
      let columns = [...baseColumns].map(col => {
        let show = col.show;
        let width = col.width;
        let localField = localColumns[col.field];
        if (null != localField) {
          width = typeof localField.width == 'number'
            ? `${localField.width}px`
            : `${localField.width}`.indexOf('px') ? localField.width : '';
          show = localField.show !== false;
        }
        col.show = show;
        col.width = width;
        col.type = 'column';

        return col;
      });

      if (this.isBasicEditionHideProduct) {
        columns = columns.filter(item => item.field !== 'esProductEntities')
      }
      // 没有编辑权限移除编辑这一列
      if(!this.allowEdit) {
        columns = columns.filter(item => (item.field !== 'operate'))
      }

      // 是否隐藏销售单价和出库价
      if(!this.serviceProviderShowPrice) {
        columns = columns.filter(field => field.fieldName !== 'salePrice' && field.fieldName !== 'costPrice')
      }

      return columns;
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1  - 24 - 8 - 16 - 12;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        console.log(min, 'min')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    }
  },
  async mounted() {
    let initData = this.initData || {};
    this.auths = initData.authorities || {};

    // 获取缓存的pagesize
    const localStorageData = await this.getLocalStorageData();
    this.searchParams.pageSize = localStorageData[SERVICE_PRICE_PAGE_SIZE_KEY] || 10;

    this.columns = this.buildTableColumn();
    this.fetchInitData()
    this.fetchServicePriceList();
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })
  },
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [BaseTableCell.name]: BaseTableCell,
    [BatchEditingCustomerDialog.name]: BatchEditingCustomerDialog,
    [PartImport.name]: PartImport,
  }
}
</script>

<style lang="scss" scoped>
.common-list-view-header__v2 {
  align-items: center;
}
.common-list-view__v2{
  padding-bottom:0;
}
.search-input{
  width: 440px;
}

.search-input__append{
  @include backgroundColorImportant();
  color: #fff !important;
  border-radius: 0 4px 4px 0 !important;
}

.advanced-search-btn{
  @include fontColor;
}

.el-input-group__append{
  border-radius: 0 4px 4px 0;
}
.service-price-dropdown {
  white-space: nowrap;
}
</style>